package cn.clq.ymcc.listener;

import cn.clq.ymcc.domain.CourseOrder;
import cn.clq.ymcc.dto.PayDto;
import cn.clq.ymcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author clqlongbao
 * @version 1.0
 * @description: 提交订单
 * @date 2022/7/31 23:13
 */
@Slf4j
@Component
@RocketMQTransactionListener(
        txProducerGroup = "service-order-producer"  //要和发送事务消息时指明的名字一致
)
public class CourseOrderRocketMqListener implements RocketMQLocalTransactionListener {
    @Autowired
    private ICourseOrderService courseOrderService;
    /**
     * @description: 执行本地事务，保存主订单和子订单
     * @param: message  o
     * @return: org.apache.rocketmq.spring.core.RocketMQLocalTransactionState
     * @author clqlongbao
     * @date: 2022/7/31 23:14
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        //执行本地事务，保存主订单和子订单
        log.info("执行本地事务");
        if(arg == null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        try {
            CourseOrder courseOrder = (CourseOrder) arg;
            //保存主订单和子订单
            courseOrderService.saveOrderAndItems(courseOrder);
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;//执行本地事务失败
        }
        return RocketMQLocalTransactionState.COMMIT;//执行本地事务成功
    }

    /**
     * @description: 检查本地事务，检查主订单和子订单是否保存成功
     * @param: message
     * @return: org.apache.rocketmq.spring.core.RocketMQLocalTransactionState
     * @author clqlongbao
     * @date: 2022/7/31 23:14
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 根据消息体去查询本地事务是否已经执行成功
        // 需要将消息体反序列化，byte[] --> jsonString   -->PayDto 对象
        log.info("检查本地事务状态");
        try {
            //Message对象本身就是一个byte[]，所以这里可以直接强转
            byte[] bytOjb = (byte[])message.getPayload();
            String messgeStr = new String(bytOjb, StandardCharsets.UTF_8);
            PayDto payDto = JSONObject.parseObject(messgeStr, PayDto.class);
            CourseOrder courseOrder = courseOrderService.selectOrderByOrderNo(payDto.getOrderNo());
            System.out.println("主子订单保存成功");
            return courseOrder == null?RocketMQLocalTransactionState.ROLLBACK:RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
